import { Router } from 'express';
import oauthController from '@/controller/oauthController';
import { authenticate } from '@/middleware/auth';
import validateSchema from '@/middleware/validateSchema';
import z from 'zod';

const router = Router();

// OAuth 生成授权URL的验证 schema
const generateAuthUrlSchema = z.object({
    params: z.object({
        provider: z
            .string()
            .min(1, 'OAuth 提供商不能为空')
            .refine(
                (val) => ['google', 'github', 'twitter'].includes(val.toLowerCase()),
                {
                    message: '不支持的 OAuth 提供商，仅支持 google, github'
                }
            ),
    }),
    query: z.object({
        action: z
            .enum(['login', 'link'], {
                errorMap: () => ({ message: '操作类型必须是 login 或 link' })
            }),
        userId: z
            .string()
            .optional()
            .refine(
                (val) => !val || val.length > 0,
                { message: '用户ID不能为空字符串' }
            ),
    }),
});

// OAuth 回调验证 schema
const callbackSchema = z.object({
    params: z.object({
        provider: z
            .string()
            .min(1, 'OAuth 提供商不能为空')
            .refine(
                (val) => ['google', 'github', 'twitter'].includes(val.toLowerCase()),
                {
                    message: '不支持的 OAuth 提供商'
                }
            ),
    }),
    query: z.object({
        code: z.string().optional(),
        state: z.string().optional(),
        error: z.string().optional(),
    }).refine(
        (data) => data.code || data.error,
        {
            message: '必须提供 code 或 error 参数',
            path: ['code']
        }
    ),
});

// 解绑账户验证 schema
const unlinkAccountSchema = z.object({
    params: z.object({
        provider: z
            .string()
            .min(1, 'OAuth 提供商不能为空')
            .refine(
                (val) => ['google', 'github', 'twitter'].includes(val.toLowerCase()),
                {
                    message: '不支持的 OAuth 提供商'
                }
            ),
    }),
});

// 绑定账户验证 schema
const linkAccountSchema = z.object({
    params: z.object({
        provider: z
            .string()
            .min(1, 'OAuth 提供商不能为空')
            .refine(
                (val) => ['google', 'github', 'twitter'].includes(val.toLowerCase()),
                {
                    message: '不支持的 OAuth 提供商'
                }
            ),
    }),
    query: z.object({
        code: z
            .string()
            .min(1, '授权码不能为空'),
        state: z
            .string()
            .min(1, '状态参数不能为空'),
    }),
});

/**
 * @route GET /oauth/:provider/auth
 * @desc 生成OAuth授权URL
 * @access Public
 * @param {string} provider - OAuth提供商 (google)
 * @query {string} action - 操作类型 (login|link)
 * @query {string} userId - 用户ID (仅用于绑定账户)
 */
router.get(
    '/:provider/auth',
    validateSchema(generateAuthUrlSchema),
    oauthController.generateAuthUrl
);

/**
 * @route GET /oauth/:provider/callback
 * @desc 处理OAuth回调
 * @access Public
 * @param {string} provider - OAuth提供商 (google)
 * @query {string} code - 授权码
 * @query {string} state - 状态参数
 * @query {string} error - 错误信息
 */
router.get(
    '/:provider/callback',
    validateSchema(callbackSchema),
    oauthController.handleCallback
);

/**
 * @route GET /oauth/accounts
 * @desc 获取用户的OAuth账户列表
 * @access Private
 */
router.get('/accounts', authenticate, oauthController.getUserAccounts);

/**
 * @route DELETE /oauth/accounts/:provider
 * @desc 解绑OAuth账户
 * @access Private
 * @param {string} provider - OAuth提供商 (google)
 */
router.delete(
    '/accounts/:provider',
    authenticate,
    validateSchema(unlinkAccountSchema),
    oauthController.unlinkAccount
);

/**
 * @route POST /oauth/accounts/:provider/link
 * @desc 绑定OAuth账户到现有用户
 * @access Private
 * @param {string} provider - OAuth提供商 (google)
 * @query {string} code - 授权码
 * @query {string} state - 状态参数
 */
router.post(
    '/accounts/:provider/link',
    authenticate,
    validateSchema(linkAccountSchema),
    oauthController.linkAccount
);

export default router; 